﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FanPages.Server.Services.Contracts;
using FanPages.Server.Repostory.EFRepository.Model;
using FanPages.Common.DataAccess;
using FanPages.Server.Services.Transformers;
using FanPages.Common.Exceptions;
using FanPages.Server.Services.Contracts.Dto;

namespace FanPages.Server.Services
{
    public class SearchExceptionService : ISearchExceptionService
    {
        IRepository<SearchException> repository = new EFRepository<SearchException>(new FanPagesEntities());

        public void Save(Contracts.Dto.SearchExceptionDto searchException)
        {
            try
            {
                if (searchException.Id != 0)
                {
                    SearchException item = repository.First(x=> x.Id == searchException.Id);
                    repository.Update(new SearchExceptionTransformerSvc().ToExistingClient(searchException, item));
                }
                else
                {
                    repository.Add(new SearchExceptionTransformerSvc().ToClient(searchException));
                }
            }
            catch (Exception ex)
            {
                throw new ServiceException("SearchExceptionService.Save exception", ex);
            }
        }

        public void Delete(Contracts.Dto.SearchExceptionDto searchException)
        {
            try
            {
                repository.Delete(repository.First(x=> x.Id == searchException.Id));
            }
            catch (Exception ex)
            {
                throw new ServiceException("SearchExceptionService.Delete exception", ex);
            }
        }

        public List<SearchExceptionDto> GetByFanItem(Contracts.Dto.FanItemDto fanItem)
        {
            try
            {
                var search = repository.Find(x => x.FanItem.Id == fanItem.Id).ToList();
                return new SearchExceptionTransformerSvc().ToListDto(search);
            }
            catch (Exception ex)
            {
                throw new ServiceException("SearchExceptionService.GetByFanItem exception", ex);
            }
        }

        public Contracts.Dto.SearchExceptionDto GetById(int id)
        {
            try
            {
                var search = repository.First(x => x.Id == id);
                return new SearchExceptionTransformerSvc().ToDto(search);
            }
            catch (Exception ex)
            {
                throw new ServiceException("SearchExceptionService.GetById exception", ex);
            }
        }
    }
}
